package repo

import (
	"astgram/dal/po"
	"github.com/jinzhu/gorm"
)

type ImageRepo struct {
	db *gorm.DB
}

func NewImageRepo() *ImageRepo {
	return &ImageRepo{
		db: GetDB().Debug(),
	}
}

func (repo *ImageRepo) GetImagesPos(limit int64, offset int64, id int64) ([]*po.Image, int64, error) {
	var pos []*po.Image
	var total int64
	sql := repo.db.Model(&po.Image{})
	if id != 0 {
		sql = sql.Where("id = ?", id)
	}
	sql = sql.Limit(limit)
	sql = sql.Offset(offset)
	sql = sql.Order("id desc")
	err := sql.Find(&pos).Error
	if err != nil {
		return nil, 0, err
	}
	err = sql.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}
	return pos, total, nil
}

func (repo *ImageRepo) CreateImage(imagePo *po.Image) error {
	sql := repo.db.Model(&po.Image{})
	return sql.Omit("id").Create(imagePo).Error
}
